package com.itheima.Demo;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;


import java.io.InputStream;
import java.util.List;


public class Demo {

    private SqlSession sqlSession;
    private InputStream is;

    @Before
    public void init()throws Exception{
        //加载核心配置文件
       is= Resources.getResourceAsStream("MyBatisConfig.xml");
       //获取Sqlsession工厂对象
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
        //通过SqlSession工厂对象获取SqlSession对象
        sqlSession=factory.openSession();
        //执行映射配置文件中的sql语句，并接收结果
        //处理结果

    }

    //释放资源
    @After
    public void destory()throws Exception{
        sqlSession.commit();
        sqlSession.close();
        is.close();
    }


    @Test
    public void findAll()throws Exception{
        List<User> users = sqlSession.selectList("UserMapper.findAll");
        for (User u : users) {
            System.out.println(u);
        }
    }

        //根据id查询
    @Test
    public void findById() throws Exception {
        User u = sqlSession.selectOne("UserMapper.findById", 21);
        System.out.println(u);
    }

        //查询总记录数
    @Test
    public void findCount()throws Exception{
        int count = sqlSession.selectOne("UserMapper.findCount");
        System.out.println(count);
    }

        //模糊查询
        @Test
    public void findByName()throws Exception{
            List<User> users = sqlSession.selectList("UserMapper.findByName", "王");
            for (User u : users) {
                System.out.println(u);
            }
        }


               //模糊查询2
               @Test
               public void findByName2() throws Exception{
                   List<User> users = sqlSession.selectList("UserMapper.findByName2", "张");
                   for (User u : users) {
                       System.out.println(u);
                   }
               }

                //添加数据。并返回最后添加数据的id
               @Test
               public void saveReturnId(){
                   User u=new User();
                   u.setName("潭州");
                   u.setGender("男");
               System.out.println("保存之前"+u);
               sqlSession.insert("UserMapper.saveReturnId",u);
               System.out.println("保存之后"+u);



}
            //添加数据。并返回最后添加数据的id
                    @Test
                    public void saveReturnId2(){
                    User u=new User();
                    u.setName("金宝");
                    u.setGender("女");
                    System.out.println("保存之前："+u);
                    sqlSession.insert("UserMapper.saveReturnId2",u);
                    System.out.println("保存之后："+u);

}










}
